<?php

namespace App\Controllers\Experience;

use App\Models\Goods\Goods;
use App\Models\Experience\ExpGoods;
use App\Models\Experience\ExpOrder;
class GetExpGoods extends \App\Libs\Base\BaseAction
{
    protected function beforeRun()
    {
        parent::beforeRun();
        //$this->needLogin = TRUE;
    }


    public function execute()
    {
        $page = $this->request->get('page', 'int', 1);
        $enum = $this->request->get('enum', 'int', 5);
        if(!$this->request->has('city')){
            return \App\Libs\Views\Json::view(1, '没有指定城市', null);
        }
        $city = $this->request->get('city');
        $offset = ($page - 1) * $enum;
        //找到所有可以申请的商品
	//限制：要显示，要时间正确:;
        $allExpGoods = ExpGoods::findAll([
            'conditions' => 'show_status=?1 and unix_timestamp(end_time)>?2 and unix_timestamp(start_time)<?2 and city=?3',
            'columns' => 'id,gid,label_url,num as sum_num,end_time,start_time',
            'order' => 'apply desc,end_time desc',
            'limit' => $enum,
            'offset' => $offset,
            'bind' => [1 => '2', 2 => time(),3=>$city],
        ])->toArray();
        //没有体验商品：
        if (empty($allExpGoods)) {
            return \App\Libs\Views\Json::view(1, '暂没有体验商品', null);
        }
        //得到商品ID
        foreach ($allExpGoods as $key => $val) {
            $expGoodsId[] = $val['gid'];
        }
        //得到商品信息数组
        $transFormGoodInfo = Goods::getGoodsInfoforExpGoodsList($expGoodsId, 'id as gid,goods_name,goods_price,sale_price,goods_img','gid');
        //格式化价格；
        foreach($transFormGoodInfo as $key => $val){
            $priceArray['goods_price'] = Goods::formatPrice($val['goods_price']);
            $priceArray['sale_price'] = Goods::formatPrice($val['sale_price']);
            $transFormGoodInfo[$key] = array_merge($val,$priceArray);
        }
        foreach ($allExpGoods as $key => $val) {
            if (isset($transFormGoodInfo[$allExpGoods[$key]['gid']])) {
                $finalExpGoods[] = array_merge($allExpGoods[$key], $transFormGoodInfo[$allExpGoods[$key]['gid']]);
            }else{
                //违反事实，
                //此处一定要求：体验商品一定对应有商品，否则出错
                $finalExpGoods[] = array_merge($allExpGoods[$key], []);
            }
        }
        //得到申请ID，以便去订单表中查找多少人申请了
        foreach ($allExpGoods as $key => $val) {
            $expId[] = $val['id'];
        }
        //查找已经申请了多少人了
        $haveApplyData = ExpOrder::getAppliesOfGoods($expId, 'eid');
        foreach ($finalExpGoods as $key => $val) {
            if (isset($haveApplyData[$finalExpGoods[$key]['id']])) {
                $finalExpGoods[$key]['haveApply'] = $haveApplyData[$finalExpGoods[$key]['id']]['count'];
            }else{
                $finalExpGoods[$key]['haveApply'] = 0;
            }
        }
        return \App\Libs\Views\Json::view(0, '成功', $finalExpGoods);
    }
}
